#!/bin/bash

# VNC WebSocket代理启动脚本

# 检查websockify是否安装
if ! command -v websockify &> /dev/null; then
    echo "websockify 未安装，正在安装..."

    # 尝试使用pip安装
    if command -v uv &> /dev/null; then
        uv tool install websockify
        echo "错误: 无法安装websockify，请先安装uv工具。"
        exit 1
    fi
fi

# 启动websockify服务
# 将WebSocket端口映射到VNC端口
# 参数: $1 - WebSocket端口, $2 - VNC端口, $3 - 目标主机

WEBSOCKET_PORT=${1:-6900}
VNC_PORT=${2:-5900}
TARGET_HOST=${3:-127.0.0.1}

echo "启动VNC WebSocket代理..."
echo "WebSocket端口: $WEBSOCKET_PORT"
echo "VNC端口: $VNC_PORT"
echo "目标主机: $TARGET_HOST"

# 启动websockify
websockify --web /usr/share/novnc/ \
           --cert /etc/ssl/certs/self.pem \
           --key /etc/ssl/private/self.key \
           $WEBSOCKET_PORT \
           $TARGET_HOST:$VNC_PORT

# 如果没有证书，使用无证书模式
if [ $? -ne 0 ]; then
    echo "尝试无证书模式..."
    websockify --web /usr/share/novnc/ \
               $WEBSOCKET_PORT \
               $TARGET_HOST:$VNC_PORT
fi